<template>
    <div id="index" ref="appRef">
      <div class="bg">
        <dv-loading v-if="loading">Loading...</dv-loading>
        <div v-else class="host-body">
          <div class="d-flex jc-center">
            <dv-decoration-10 class="dv-dec-10" />
            <div class="d-flex jc-center">
              <dv-decoration-8 class="dv-dec-8" :color="decorationColors" />
              <div class="title">
                <span class="title-text">浦江专科护理操作眼科</span>
                <dv-decoration-6
                  class="dv-dec-6"
                  :reverse="true"
                  :color="['#50e3c2', '#67a1e5']"
                />
              </div>
              <dv-decoration-8
                class="dv-dec-8"
                :reverse="true"
                :color="decorationColors"
              />
            </div>
            <dv-decoration-10 class="dv-dec-10-s" />
          </div>
  
          <!-- 第二行 -->
          <div class="d-flex jc-between px-2">
            <div class="d-flex aside-width">
              <div class="react-left ml-4 react-l-s">
                <span class="react-before"></span>
                <span class="text" @click="goToHomePage">返回首页</span>
                <span class="text" @click="goToFenYangWardPage">汾阳</span>
              </div>
              <div class="react-left ml-3" style=" width:260px;">
                <span class="text">{{ subtitle[1] }}</span>
              </div>
            </div>
            <div class="d-flex aside-width">
              <div class="react-right mr-3" style="background-color: #0f1325;width:250px;" > 
                <span class="text fw-b">{{ subtitle[2]}}</span>
              </div>
              <div class="react-right mr-4 react-l-s">
                <span class="react-after"></span>
                <span class="text">
                  {{ timeInfo.dateYear }} {{ timeInfo.dateWeek }}
                  {{ timeInfo.dateDay }}
                </span>
              </div>
            </div>
          </div>
          <div class="body-box">
              <div class="WardBox">
                  <!-- 按接口返回的部门列表渲染 -->
                  <WardView  
                    v-for="dept in departments"
                    :key="dept.deptName"
                    :title="dept.deptName"
                    :statistics-data="getDeptStatistics(dept.deptName)"
                  />
            </div>
          </div>
        </div>
      </div>
    </div>
  </template>
    
  <script lang="ts">
  import { defineComponent, ref, reactive, onMounted, onUnmounted } from "vue";
  import { formatTime } from "@/utils/index";
  import { WEEK } from "@/constant/index";
  import useDraw from "@/utils/useDraw";
  import { title, subtitle, moduleInfo } from "@/constant/index";
  import { RouterLink, RouterView } from "vue-router";
  import WardView from "./WardView.vue";
  import axios from 'axios';
  
  interface StatisticsItem {
    id: string;
    iiiDataType: string;
    number: string;
    lastWeekNum: string;
    deptName: string;
  }
  
  interface Department {
    deptName: string;
  }
  
  export default defineComponent({
    components: {
      WardView
    },
    setup() {
      // * 颜色
      const decorationColors = ["#568aea", "#000000"];
      // * 加载标识
      const loading = ref<boolean>(true);
      // * 时间内容
      const timeInfo = reactive({
        setInterval: 0,
        dateDay: "",
        dateYear: "",
        dateWeek: "",
      });
      // * 适配处理
      const { appRef, calcRate, windowDraw, unWindowDraw } = useDraw();
      
      // 统计数据
      const allStatistics = ref<StatisticsItem[]>([]);
      // 部门列表
      const departments = ref<Department[]>([]);
  
      // 生命周期
      onMounted(() => {
        handleTime();
        // 加载数据
        fetchStatisticsData();
        // 屏幕适应
        windowDraw();
        calcRate();
      });
  
      onUnmounted(() => {
        unWindowDraw();
        clearInterval(timeInfo.setInterval);
      });
      // 接口请求
      const fetchStatisticsData = async () => {
        try {
  debugger;
          const response = await axios.get(
            window.globalConfig.baseApi +'/api/Nurse/GetAllStatisticsDataByDeptJson?IDataType=4&dbKey=dbPJ'
          );
          const data = response.data;
          
  debugger;
          // 过滤掉空部门名称
          allStatistics.value = data.fullStatistics.filter(
            (item: StatisticsItem) => item.deptName.trim() !== ''
          );
          
          // 过滤掉空部门并去重
          departments.value = data.departmentsOnly
            .filter((dept: Department) => dept.deptName.trim() !== '')
            .filter((v: Department, i: number, arr: Department[]) => 
              arr.findIndex(u => u.deptName === v.deptName) === i
            );
        } catch (error) {
          console.error('获取统计数据失败:', error);
        } finally {
          // 无论成功失败都关闭loading
          cancelLoading();
        }
      };
  
      // 关闭loading
      const cancelLoading = () => {
        setTimeout(() => {
          loading.value = false;
        }, 500);
      };
  
      // 处理时间监听
      const handleTime = () => {
        timeInfo.setInterval = setInterval(() => {
          const date = new Date();
          timeInfo.dateDay = formatTime(date, "HH: mm: ss");
          timeInfo.dateYear = formatTime(date, "yyyy-MM-dd");
          timeInfo.dateWeek = WEEK[date.getDay()];
        }, 1000);
      };
  
      // 获取指定部门的统计数据
      const getDeptStatistics = (deptName: string) => {
        return allStatistics.value
          .filter(item => item.deptName === deptName)
          .map(item => ({
            name: item.iiiDataType,
            value: Number(item.number)
          }));
      };
  
      return {
        loading,
        timeInfo,
        appRef,
        title,
        subtitle,
        moduleInfo,
        departments,
        getDeptStatistics
      };
    },
    methods: {
      goToHomePage() {
        this.$router.push({ name: "Index" });
      },
      goToFenYangWardPage() {
        this.$router.push({ name: "FenYangZKHLYK" });
      },
    },
  });
  </script>
    
  <style lang="scss" scoped>
  @import "../FenYangZKHLYKView/ZKHLK.scss";
  .WardBox {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  // 减小行与行之间的间距
  row-gap: 5px; /* 控制上下行之间的间距 */
  margin-bottom: 30px; /* 底部留白 */
  align-content: flex-start; /* 确保内容顶部对齐，减少额外空间 */
}

// 调整每个WardView项的外边距
.WardBox > * {
  margin: 2px 10px; /* 进一步减小上下边距 */
}
  </style>